<template>
  <!--富文本编辑器-->
  <div class="edit_container">
    <!-- 图片上传组件辅助-->
    <el-upload class="avatar-uploader" name="imgFile" :action="serverUrl" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUpload"></el-upload>
    <el-row v-loading="quillUpdateImg">
      <quill-editor v-model="editordata.content" :ref="editordata.qeref" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"></quill-editor>
    </el-row>
    <img src alt />
  </div>
</template>

<script type="text/ecmascript-6">
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image", "video"],
  ["clean"] // remove formatting button
];
import global from "@/components/global";
export default {
  props: {
    editordata: {
      type: [Object, Array],
      default: () => {
        return {
          qeref: "myQuillEditor",
          content: ""
        };
      }
    }
  },
  data() {
    return {
      quillUpdateImg: false,
      serverUrl: `${global.serverSrc}/upload`,
      img: '',
      imgUrl: "",
      // 定义富文本编辑器显示
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: value => {
                if (value) {
                  document
                    .querySelector(".avatar-uploader input")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        },
        placeholder: "请输入内容",



      }
    };
  },

  computed: {
    content() {
      return this.editordata.content;
    },
    editor() {
      console.log(this.$refs[this.editordata.qeref]);

      return this.$refs[this.editordata.qeref].quill;
    }
  },
  destroyed() {
    window.removeEventListener("keydown", ev => {
      ev.preventDefault();
    });
  },
  created() {
    // console.log(this);

    let _this = this;
    window.addEventListener("keydown", ev => {
      var ev = window.event || ev;
      if (
        ev.ctrlKey &&
        (ev.keyCode == 67 ||
          ev.keyCode == 86 ||
          ev.keyCode == 90 ||
          ev.keyCode == 88 ||
          ev.keyCode == 89)
      ) {
        _this.editordata.content = _this.datahistory;
        ev.returnValue = false;
        ev.preventDefault();
        ev.stopPropagation();
      } else {
        _this.datahistory = _this.content;
      }
    });
    if (this.noimagevideo) {
      this.editorOption.modules.toolbar.container = toolbarOptionsgg;
    } else {
      this.editorOption.modules.toolbar.container = toolbarOptions;
    }
    this.$nextTick(() => {
      let videofiles = [];
      let videos = [];
      let files = [];
      let images = [];
      let count = 0;
      let img = document.querySelectorAll(".ql-editor img");
      let video = document.querySelectorAll(".ql-editor video");
      for (let g = 0; g < img.length; g++) {
        files.push("");
        images.push({
          index: img[g].getAttribute("data-index"),
          size: Number(img[g].getAttribute("data-size")),
          file: img[g].getAttribute("src"),
          type: "image"
        });
        count += Number(img[g].getAttribute("data-size"));
      }
      for (let o = 0; o < video.length; o++) {
        videofiles.push("");
        videos.push({
          index: video[o].getAttribute("data-index"),
          size: Number(video[o].getAttribute("data-size")),
          file: video[o].getAttribute("src"),
          type: "video"
        });
        count += Number(video[o].getAttribute("data-size"));
      }
      this.videofiles = videofiles;
      this.videos = videos;
      this.files = files;
      this.images = images;
      this.allsize = count;
    });
  },
  methods: {
    // 失去焦点事件
    onEditorBlur() {
      this.$emit("editor", {
        qeref: this.editordata.qeref,
        content: this.content,
        imgUrl: this.imgUrl,
        img: this.img
      });
    },
    // 获得焦点事件
    onEditorFocus() {
      this.$emit("editor", {
        qeref: this.editordata.qeref,
        content: this.content,
        imgUrl: this.imgUrl,
        img: this.img
      });
    },
    // 内容改变事件
    onEditorChange(editor) {
      this.$emit("editor", {
        qeref: this.editordata.qeref,
        content: this.content,
        imgUrl: this.imgUrl,
        img: this.img
      });
    },
    // 富文本图片上传前
    beforeUpload() {
      // 显示loading动画
      this.quillUpdateImg = true;
    },
    //上传成功的函数
    uploadSuccess(result, file) {
      console.log(result);
      if (result.code == 0) {
        let quill = this.$refs[this.editordata.qeref].quill;
        // console.log(quill);
        let length = quill.getSelection().index;
        console.log(length);
        quill.insertEmbed(
          length,
          "image",
          global.serverSrc + result.msg
        );
        quill.setSelection(length + 1);
        this.imgUrl = global.serverSrc + result.msg;
        console.log(this.imgUrl);
        this.img = `<img src="${this.imgUrl}" />`

      }

      this.quillUpdateImg = false;
    },

    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    }
  }
};
</script>

<style scoped>
.upload-img {
  display: none;
}
</style>
